<?php

namespace app\admin\controller;

use app\admin\model\Area;
use app\admin\model\Customer;
use app\admin\model\Order;
use app\admin\model\Qudao;
use app\admin\model\Role;
use app\admin\model\Track;
use think\App;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Session;
use think\facade\View;
use think\Request;
use think\facade\Config;

class Customers extends Common
{
   protected $middleware = ['Auth'];

   public function __construct(App $app = null)
   {
      parent::__construct($app);
      $areas = Area::order('id')->all();  //地区
      $qudaos = Qudao::order('id')->all();  //来源
      $styles = config('admin.style');   //客户需求
      $dians = Config::get('admin.dian');   //店铺
      View::share(compact('areas', 'qudaos', 'styles', 'dians'));
   }

   /**
    * 显示资源列表
    * @return \think\Response
    */
   public function index(Request $request)
   {
      //模糊查询
      $where = [];
      $result = \config('admin.customers');
      //按名称
      if ($search = input('get.title')) {
         $field = $request->param('search_field');
         $fieldName = $result[$field];  //获取搜索对应的名称
         $where[] = [$field, 'like', "%" . $search . "%"];
      }
      //按时间查询
      if ($request->has('date') and $request->param('date') != '') {
         $field = $request->param('search_field');
         $fieldDate = $result[$field]; //获取搜索对应的名称
         $time = explode(" ~ ", $request->param('date'));
         $start = $time[0] . ' 00:00:00';
         $end = $time[1] . ' 23:59:59';
         $where[] = [$field, 'between time', [$start, $end]];
      }
      //按地区搜索
      if ($area_id = input('get.area_id') and $area_id != '') {
         $where[] = ['area_id', '=', $area_id];
      }
      //按来源搜索
      if ($qudao_id = $request->param('qudao_id') and $qudao_id != '') {
         $where[] = ['qudao_id', 'in', $qudao_id];
      }
      //按网销搜索
      if ($wang = $request->param('wang') and $wang != '') {
         $where[] = ['wang', 'in', $wang];
      }
      //按类型搜索
      if ($type = $request->param('type') and $type != '') {
         $where[] = ['type', 'in', $type];
      }
      //按渠道确认搜索
      if ($quren = input('get.quren') and $quren != '') {
         $where[] = ['quren', '=', $quren];
      }
      //按客户需求
      if ($style = input('get.style') and $style != '') {
         $where[] = ['style', '=', $style];
      }

      $types = config('admin.type');  //客资类型
      $qurens = config('admin.quren');  //渠道确认
      $urgents = config('admin.urgent'); //紧急客资

      $wangs = Role::with(['admins' => function ($query) {
         $query->field('name');
      }])
         ->where('name', 'A1')
         ->select();

      //查出不同用户组查看不同内容
      $admin_id = Db::table('role_admin')->whereIn('role_id', [1, 3])->column('admin_id');
      if (in_array(\session('admin.id'), $admin_id)) {
         $customers = Customer::with('area', 'qudao')
            ->where($where)
            ->order('create_at', 'desc')
            ->paginate(35, false, ['query' => request()->param()]);
      } else {
         $customers = Customer::with('area', 'qudao')
            ->where('wang <> null or wang <> ""')
            ->where($where)
            ->order('create_at', 'desc')
            ->paginate(35, false, ['query' => request()->param()]);
      }

      return view('Customers/index', compact('res', 'fieldDate', 'fieldName', 'area_id', 'types', 'qurens', 'urgents', 'styles', 'customers', 'wangs'));
   }

   /***
    * 查看日志
    */
   public function showLog(Request $request)
   {
      //查出所有操作日志
      $customerLogs = Db::table('customer_logs')
         ->where('customer_id', $request->param('log_id'))
         ->order('create_at', 'desc')
         ->select();

      return json($customerLogs);
   }

   /**
    * 显示创建资源表单页.
    *
    * @return \think\Response
    */
   public function create()
   {
      return view('Customers/create');
   }

   /**
    * 保存新建的资源
    *
    * @param  \think\Request $request
    * @return \think\Response
    */
   public function save(Request $request)
   {
      $data = $request->param();
      $data['kefu'] = Session::get('admin.name');
      $data['create_at'] = date('Y-m-d H:i:s');

      $validate = new \app\admin\validate\Customer;
      if (!$validate->check($data)) {
         return redirect('Customers/create')->with('error', $validate->getError());
      }

      $customer = Customer::create($data);

      Track::create(['customer_id' => $customer['id'], 'create_at' => $customer['create_at']]);  //增加客资到追踪表
      Order::create(['customer_id' => $customer['id'], 'create_at' => $customer['create_at']]);  //增加客资到订单表

      //写入customer_logs表日志
      $id = $customer['id'];
      $content = session::get('admin.name') . '录入客资' . $customer['id'];
      $this->log($id, $content);

      return redirect('Customers/index')->with('success', '录入客资成功');
   }

   /**
    * 更新客资信息,5是A1组
    */
   public function edit_customer(Request $request)
   {
      $name = $request->param('name');
      $data['id'] = $request->param('id');
      $data[$name] = $request->param('val');

      $role_id = Db::table('role_admin')->where('admin_id', \session('admin.id'))->column('role_id');
      if (in_array(5, $role_id) || in_array(6, $role_id)) {
         $res = Customer::where('id', $data['id'])->where('wang', \session('admin.name'))->update($data);
         if (!$res) {
            return json(['status' => 0, 'msg' => '无权操作~']);
         }
      } else {
         Customer::update($data);
      }

      //写入customer_logs表日志
      $this->addLog($name, $data);
   }

   /***
    * 记录操作日志
    */
   public function addLog($name, $data)
   {
      $customers = \config('admin.customers');
      $areas = Area::order('id')->all();  //地区
      $qurens = config('admin.quren');  //渠道确认
      $types = config('admin.type');  //客资类型
      $styles = config('admin.style');   //客户需求

      if ($name == 'area_id') {
         $res = $areas[$data[$name]]['name'];
      } elseif ($name == 'quren') {
         $res = $qurens[$data[$name]];
      } elseif ($name == 'type') {
         $res = $types[$data[$name]];
      } elseif ($name == 'style') {
         $res = $styles[$data[$name]];
      } else {
         $res = $data[$name];
      }

      $id = $data['id'];
      $content = session::get('admin.name') . '更新客资' . $id . '[' . $customers[$name] . ']为' . $res;
      $this->log($id, $content);
   }


   /***
    * 改变属性
    */
   public function change(Request $request)
   {
      $customer = Customer::find($request->param('id'));
      $attr = $request->param('attr');
      $customer->$attr = !$customer->$attr;
      $customer->save();
   }

   /***
    * 多选删除
    */
   public function delete_all(Request $request)
   {
      Customer::destroy($request->param('check_id'));
      //同时删除tracks和orders表
      Track::whereIn('customer_id', $request->param('check_id'))->delete();
      Order::whereIn('customer_id', $request->param('check_id'))->delete();

      //写入customer_logs表日志
      $content = session::get('admin.name') . '删除了客资' . implode(',', $request->param('check_id'));
      $this->log($id = '', $content);
   }

   /****
    * 写入日志表
    */
   public function log($id, $content)
   {
      $log['customer_id'] = $id;
      $log['name'] = session::get('admin.name');
      $log['log'] = $content;
      $log['create_at'] = date('Y-m-d H:i:s');
      Db::table('customer_logs')->insert($log);
   }


   /***
    * 导出
    */
   public function export_customer()
   {
      $areas = Area::order('id')->all();  //地区
      $qudaos = Qudao::order('id')->all();  //来源
      $qurens = config('admin.quren');  //渠道确认
      $types = config('admin.type');  //客资类型
      $styles = config('admin.style');   //客户需求

      $customers = \config('admin.customers');
      $name = '客资列表';
      $data = Db::table('customers')->order('id', 'desc')->select();
      foreach ($data as &$item) {
         $item['area_id'] = $item['area_id'] ? $areas[$item['area_id']]['name'] : '未选择';  //地域
         $item['qudao_id'] = $item['qudao_id'] ? $qudaos[$item['qudao_id']]['name'] : '未选择'; //来源
         $item['quren'] = $item['quren'] ? $qurens[$item['quren']] : '未选择';
         $item['type'] = $item['type'] ? $types[$item['type']] : '未选择';
         $item['style'] = $item['style'] ? $styles[$item['style']] : '未选择';
      }

      export($customers, $data, $name);
   }


}
